package com.innerchic.huhu.http;

import android.util.Log;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * ================================================
 * 作    者：贾恒飞 >>> 17515250730@163.com
 * 项    目：watcher-demo
 * 日    期：2021/12/17 14:58
 * 包    名：com.innerchic.communication.http
 * 描    述：请求回调
 * Create by zFox from AndroidStudio4.2
 * ================================================
 */
public abstract class HttpCallback implements Callback {

    protected final static String TAG = "Watcher-http";

    @Override
    public void onFailure(@NotNull Call call, @NotNull IOException e) {
        String errorMessage = e.getMessage() == null ? "请求失败,未知的错误." : e.getMessage();
        onFailure(errorMessage);
    }

    @Override
    public void onResponse(@NotNull Call call, @NotNull Response response) {
        int code = response.code();
        if (code == 200) {
            ResponseBody body = response.body();
            if (body == null) {
                onAccident();
            } else {
                onSuccess(true, body);
            }
        } else {
            String message = response.message();
            message = "请求错误,错误码[" + response.code() + "] => 错误信息为: " + message;
            onError(message);
        }
    }

    public abstract void onSuccess(boolean isSuccess, ResponseBody body);

    public void onAccident() {
        Log.d(TAG, "超出预期的结果,结果对象为null");
    }

    public void onError(String errorMessage) {
        Log.d(TAG, errorMessage);
    }

    public void onFailure(String failMessage) {
        Log.d(TAG, "请求时失败,错误信息为:" + failMessage);
    }

}
